<?php

class Hotel extends CActiveRecord
{
	public $titleDetailes;
	
	public function tableName()
	{
		return lfirst(__CLASS__);
	}
	
	public static function model($className = __CLASS__)
    {
    	return parent::model(lfirst(__CLASS__));
    }
    
    public function rules()
    {
    	return array(
            array('title, cityId', 'required'),
            array('stars', 'length', 'min' => 0, 'max' => 5)
    	);
    }
    
	public function relations()
	{
		return array(
	        'excursions'    => array(self::HAS_MANY, 'Hotel2excursion', 'hotelId'),
			'hotelFeatures' => array(self::HAS_MANY, 'Hotel2hotelFeature', 'hotelId'),
			'roomFeatures'  => array(self::HAS_MANY, 'Hotel2roomFeature', 'hotelId'),
			'hotelDates'	=> array(self::HAS_MANY, 'HotelDateGroup', 'hotelId'),
			'hotelPhotos'   => array(self::HAS_MANY, 'HotelPhoto', 'hotelId', 'order'=>'??.id asc'),
			'city'			=> array(self::BELONGS_TO, 'City', 'cityId', 'alias' => 'city'),
	    );
	}
	
	public function criteria($sort = 'hoteltitle', $order = 'asc', $start = false, $limit = false)
	{
		$params = array();
		$thisTableName = $this->tableName();
		
    	if ($sort == 'hoteltitle') {
    		$sort = $thisTableName . '.title';
    	} elseif ($sort == 'citytitle') {
    		$sort = 'city.title';
    	} elseif ($sort == 'id') {
    		$sort = $thisTableName . '.id';
    	}
    	
		$params['order'] = $sort . ' ' . $order;
    	
    	if ($start !== false) {
    		$params['offset'] = intval($start);
    	}
    	
    	if ($limit !== false) {
    		$params['limit'] = intval($limit);
    	}
    	
		$this->getDbCriteria()->mergeWith($params);
    	
    	return $this;
	}
	
	public function addStarsHtml2title()
	{
		$stars    = "repeat('<div class=\"starRatingDiv\"></div>', stars) as titleDetailes";
		$criteria = new CDbCriteria();
		$criteria->select = array('*', new CDbExpression($stars));
		$criteria->order  = 'title asc';
		
		$this->getDbCriteria()->mergeWith($criteria);
		
		return $this;
	}
	
	public function searchHotels($keywords)
	{
		$criteria = new CDbCriteria();
		
		$criteria->condition = "match(title, description) against('{$keywords}' in boolean mode)";
		$criteria->order = 'title asc';
		
		return self::model()->addStarsHtml2title()->findAll($criteria);
	}
	
	public function getAdvancedSearchData($searchParams, $options)
	{
		$sql = "select h.id,
       				   concat('<a href=\"javascript: openLink(\'/hotel/detailed/id/', h.id, '/\');\">', h.title, '</a>') as hotel,
				       c.title as city,
				       h.stars as stars,
				       hr.title as room,
				       hd.dateStart as dateStart,
				       hd.dateEnd as dateEnd,
				       hrad.price as price
				  from hotelRoomAndDates as hrad
				    inner join hotelRoom as hr on hrad.hotelRoomId = hr.id
				    inner join hotelDateGroup as hdg on hdg.id = hrad.hotelDateGroupId
				    inner join hotelDate as hd on hd.hotelDateGroupId = hdg.id
				    inner join hotel as h on h.id = hdg.hotelId
				    inner join city as c on c.id = h.cityId
				  where hd.dateStart >= '" . $searchParams['date1'] . "' 
				    and hd.dateEnd  <= '" . $searchParams['date2'] . "' 
				    and hrad.price >= " .  $searchParams['price1'] . "
		            and hrad.price <= " . $searchParams['price2'] . ' ' . 
					(intval($searchParams['stars']) > 0 ? ' and h.stars = ' . intval($searchParams['stars']) . ' ' : '') .
					(count($searchParams['cityIds']) > 0 ? ' and c.id in (' . implode(',', $searchParams['cityIds']) . ') ' : '') .
					(count($searchParams['hotelIds']) > 0 ? ' and h.id in (' . implode(',', $searchParams['hotelIds']) . ') ' : '') .
					(strlen($searchParams['hotelTitle']) > 0 ? " and h.title like " . (Yii::app()->db->quoteValue('%' . $searchParams['hotelTitle'])) . " " : '') .
				' order by ' . $options['sidx'] . ' ' . $options['sord'] . 
				' limit ' . intval($options['limit'] * $options['page'] - $options['limit']) . ',' . intval($options['limit']);
					
		$command = Yii::app()->db->createCommand($sql);
    	
		return $command->queryAll();
	}
	
	public function getAdvancedSearchCount($searchParams)
	{
		$sql = "select count(*) as c
				  from hotelRoomAndDates as hrad
				    inner join hotelRoom as hr on hrad.hotelRoomId = hr.id
				    inner join hotelDateGroup as hdg on hdg.id = hrad.hotelDateGroupId
				    inner join hotelDate as hd on hd.hotelDateGroupId = hdg.id
				    inner join hotel as h on h.id = hdg.hotelId
				    inner join city as c on c.id = h.cityId
				  where hd.dateStart >= '" . $searchParams['date1'] . "' 
				    and hd.dateEnd  <= '" . $searchParams['date2'] . "' 
				    and hrad.price >= " .  $searchParams['price1'] . "
		            and hrad.price <= " . $searchParams['price2'] . ' ' . 
					(intval($searchParams['stars']) > 0 ? ' and h.stars = ' . intval($searchParams['stars']) . ' ' : '') .
					(count($searchParams['cityIds']) > 0 ? ' and c.id in (' . implode(',', $searchParams['cityIds']) . ') ' : '') .
					(count($searchParams['hotelIds']) > 0 ? ' and h.id in (' . implode(',', $searchParams['hotelIds']) . ') ' : '') .
					(strlen($searchParams['hotelTitle']) > 0 ? " and h.title like " . (Yii::app()->db->quoteValue('%' . $searchParams['hotelTitle'])) . " " : '');
					
		$command = Yii::app()->db->createCommand($sql);
    	
		return $command->queryAll();
	}
	
	public static function getImagesConfig()
	{
		$config = new CConfiguration('protected/config/images.php');
		$config = $config->toArray();
		
		return $config['hotel'];
	}
    
    public function saveExcursions($hotelId, $dataStr)
    {
    	$dataStr = trim($dataStr);
    	
    	Hotel2excursion::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	if ($dataStr != '') {
    		$data = explode(',', $dataStr);
    		if (count($data) > 0) {
    			foreach($data as $val) {
    				$hotel2excursion = new Hotel2excursion();
    				$hotel2excursion->hotelId = intval($hotelId);
    				$hotel2excursion->excursionId = intval($val);
    				$hotel2excursion->save();
    			}
    		}
    	}
    }
    
    public function saveHotelFeatures($hotelId, $dataStr)
    {
        $dataStr = trim($dataStr);
        
        Hotel2hotelFeature::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	if ($dataStr != '') {
    		$data = explode(',', $dataStr);
    		if (count($data) > 0) {
    			foreach($data as $val) {
    				$hotel2hotelFeature = new Hotel2hotelFeature();
    				$hotel2hotelFeature->hotelId = intval($hotelId);
    				$hotel2hotelFeature->hotelFeatureId = intval($val);
    				$hotel2hotelFeature->save();
    			}
    		}
    	}
    }
    
    public function saveRoomFeatures($hotelId, $dataStr)
    {
		$dataStr = trim($dataStr);
		
		Hotel2roomFeature::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	if ($dataStr != '') {
    		$data = explode(',', $dataStr);
    		if (count($data) > 0) {
    			foreach($data as $val) {
    				$hotel2roomFeature = new Hotel2roomFeature();
    				$hotel2roomFeature->hotelId = intval($hotelId);
    				$hotel2roomFeature->roomFeatureId = intval($val);
    				$hotel2roomFeature->save();
    			}
    		}
    	}
    }
    
    public function saveHotelDates($hotelId, $data)
    {
    	/*HotelDate::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	foreach ($data as $val) {
    		$hotelDate = new HotelDate();
    		if ((trim(strval($val))) != '') {
    			$tmpArr = explode('/', $val);
    			$hotelDate->hotelId = $hotelId;
    			$hotelDate->date = $tmpArr[2] . '-' . $tmpArr[1] . '-' . $tmpArr[0];
    			$hotelDate->save();
    		}
    	}*/
    }
    
    public function uploadPhotos($hotelId)
    {
    	$imagesConfig = $this->getImagesConfig();
    	
    	for ($i = 0; $i < $imagesConfig['maxPhotos']; $i++) {
    		$hotelPhoto = new HotelPhoto();
    		$hotelPhoto->hotelId = intval($hotelId);
    		$hotelPhoto->photo = CUploadedFile::getInstance($hotelPhoto, $i);
			
    		if ($hotelPhoto->photo) {
    			$this->savePhoto($hotelPhoto, (microtime(true) * 10000) . $i);
    		}
    	}
    }
    
    public function savePhoto($photoObj, $prefix)
    {
    	$imagesConfig = $this->getImagesConfig();
    	
  		$ext = $photoObj->photo->getExtensionName();
    	$imageName = $prefix . '.' . $ext;
    		
    	$bigImage    = $_SERVER['DOCUMENT_ROOT'] . $imagesConfig['uploadPath'] . $imagesConfig['bigImgPrefix'] . '_' . $imageName;
    	$mediumImage = $_SERVER['DOCUMENT_ROOT'] . $imagesConfig['uploadPath'] . $imagesConfig['mediumImgPrefix'] . '_' . $imageName;
    	$smallImage  = $_SERVER['DOCUMENT_ROOT'] . $imagesConfig['uploadPath'] . $imagesConfig['smallImgPrefix'] . '_' . $imageName;
    			
    	$photoObj->photo->saveAs($bigImage);
    			
    	$loadedImg = Yii::app()->image->load($bigImage);
    	
    	$dontResizeBig    = false;
    	$dontResizeMedium = false;
    	$dontResizeSmall  = false;
    	
    	if ($loadedImg->width > $loadedImg->height) {
    		if ($loadedImg->width < $imagesConfig['maxWidth']) {
    			$dontResizeBig = true;
    		}
    		if ($loadedImg->width < $imagesConfig['mediumWidth']) {
    			$dontResizeMedium = true;
    		}
    		if ($loadedImg->width < $imagesConfig['minWidth']) {
    			$dontResizeSmall = true;
    		}
    	} else {
    		if ($loadedImg->height < $imagesConfig['maxHeight']) {
    			$dontResizeBig = true;
    		}
    		if ($loadedImg->height < $imagesConfig['mediumHeight']) {
    			$dontResizeMedium = true;
    		}
    		if ($loadedImg->height < $imagesConfig['minHeight']) {
    			$dontResizeSmall = true;
    		}
    	}
    	
    	if (!$dontResizeBig) {
    		Yii::app()->image->load($bigImage)->resize($imagesConfig['maxWidth'], $imagesConfig['maxHeight'], Image::AUTO)->quality($imagesConfig['quality'])->save();    		
    	} else {
    		Yii::app()->image->load($bigImage)->quality($imagesConfig['quality'])->save();
    	}
    	
    	if (!$dontResizeMedium) {
    		Yii::app()->image->load($bigImage)->resize($imagesConfig['mediumWidth'], $imagesConfig['mediumHeight'], Image::AUTO)->quality($imagesConfig['quality'])->save($mediumImage);    		
    	} else {
    		Yii::app()->image->load($bigImage)->quality($imagesConfig['quality'])->save($mediumImage);
    	}
    	
    	if (!$dontResizeSmall) {
    		Yii::app()->image->load($bigImage)->resize($imagesConfig['minWidth'], $imagesConfig['minHeight'], Image::AUTO)->quality($imagesConfig['quality'])->save($smallImage);    		
    	} else {
    		Yii::app()->image->load($bigImage)->quality($imagesConfig['quality'])->save($smallImage);    		
    	}

		if (intval($photoObj->id) == 0) {
    		$photoObj->image = $imageName;
    		$photoObj->save();
		} else {
			HotelPhoto::model()->updateByPk(intval($photoObj->id), array('image' => $imageName));
		}
    }
    
    public function reloadPhotos($hotelId, $idOfPhotos4reload, $idOfPhotos4remove)
    {
    	$reloadedPhotosIds = array();
    	$newUploadArray    = $_FILES['HotelPhoto']['name'];
    	
    	if (count($idOfPhotos4reload) > 0) {
    		foreach ($idOfPhotos4reload as $val) {
    			$key = 'reload' . $val;
    			if (array_key_exists($key, $newUploadArray) && strval($newUploadArray[$key]) != '') {
    				$photo = HotelPhoto::model()->findByPk($val);
    				$this->removePhotoFile($photo->attributes['image']);
    				
    				$hotelPhoto = new HotelPhoto();
    				$hotelPhoto->hotelId = intval($hotelId);
    				$hotelPhoto->photo   = CUploadedFile::getInstance($hotelPhoto, $key);
    				
    				if ($hotelPhoto->photo) {
    					$hotelPhoto->id = $val;
    					$this->savePhoto($hotelPhoto, (microtime(true) * 10000) . $val);
    					$reloadedPhotosIds[] = $val;
    				}
    			}
    		}
    	}
    	
    	if (count($idOfPhotos4remove) > 0) {
	    	foreach ($idOfPhotos4remove as $value) {
	    		if (!in_array($value, $reloadedPhotosIds)) {
	    			$this->removePhoto($value);
	    		}
	    	}
    	}
    	
		$this->uploadPhotos($hotelId);
    }
    
    public function removeAllConnections($hotelId)
    {
    	Hotel2excursion::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	Hotel2hotelFeature::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	Hotel2roomFeature::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	$hotelDateGroups = HotelDateGroup::model()->findAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	HotelDateGroup::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	HotelRoom::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
    	
    	foreach ($hotelDateGroups as $hotelDateGroupKey => $hotelDateGroupValue) {
    		HotelDate::model()->deleteAll('hotelDateGroupId=:hotelDateGroupId', array(':hotelDateGroupId' => intval($hotelDateGroupValue->id)));
    		HotelRoomAndDates::model()->deleteAll('hotelDateGroupId=:hotelDateGroupId', array(':hotelDateGroupId' => intval($hotelDateGroupValue->id)));
    	}
    	
    	$findData = HotelPhoto::model()->findAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
		HotelPhoto::model()->deleteAll('hotelId=:hotelId', array(':hotelId' => intval($hotelId)));
		
		$imagesConfig = $this->getImagesConfig();
    	
    	if (count($findData) > 0) {
    		foreach ($findData as $value) {
    			$this->removePhotoFile($value['image']);
    		}
    	}
    }
    
    public function removePhoto($id)
    {
    	$photo = HotelPhoto::model()->findByPk($id);
    	if ($photo) {
    		$this->removePhotoFile($photo->attributes['image']);
    		HotelPhoto::model()->deleteByPk($photo->attributes['id']);
    	}
    }
    
    public function removePhotoFile($image)
    {
    	$imagesConfig = $this->getImagesConfig();
    	
    	$bimImg   = $_SERVER['DOCUMENT_ROOT'] . $imagesConfig['uploadPath'] . $imagesConfig['bigImgPrefix'] . '_' . $image;
    	$mediumImg= $_SERVER['DOCUMENT_ROOT'] . $imagesConfig['uploadPath'] . $imagesConfig['mediumImgPrefix'] . '_' . $image;
    	$smallImg = $_SERVER['DOCUMENT_ROOT'] . $imagesConfig['uploadPath'] . $imagesConfig['smallImgPrefix'] . '_' . $image;
    	
    	if (file_exists($bimImg)) {
    		unlink($bimImg);
    	}
    	
    	if (file_exists($mediumImg)) {
    		unlink($mediumImg);
    	}
    			
    	if (file_exists($smallImg)) {
    		unlink($smallImg);
    	}
    }
}